package com.google.code.stalkernet.example.ui.action;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.nio.charset.Charset;
import java.util.Random;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import com.google.code.stalkernet.database.Database;
import com.google.code.stalkernet.entry.EntryUtils;
import com.google.code.stalkernet.reactor.Reactor;

public class AddNEntriesAction extends AbstractAction
{
    private final static Charset UTF8 = Charset.forName ("UTF-8");
    private final static Random random = new Random ();

    private final Reactor reactor;
    private final Database database;

    public AddNEntriesAction (Reactor reactor, Database database)
    {
        super ("Add N Entries");

        if (reactor == null)
            throw new IllegalArgumentException ("Reactor is null");

        if (database == null)
            throw new IllegalArgumentException ("Database is null");

        this.reactor = reactor;
        this.database = database;
    }

    @Override
    public void actionPerformed (ActionEvent e)
    {
        String numberOfEntries = (String)JOptionPane.showInputDialog(
            (Component)e.getSource (), "Number of entries:", "Add N Entries",
            JOptionPane.PLAIN_MESSAGE, null, null, "1000");

        if (numberOfEntries != null)
        {
            try
            {
                final int n = Integer.parseInt (numberOfEntries);

                reactor.invoke (
                    new Runnable()
                    {
                        @Override
                        public void run ()
                        {
                            for (int i = 0; i < n; i++)
                                database.addEntry (database.createEntry (
                                    EntryUtils.createEntryBody (
                                        ("entry" + (random.nextInt (900000) +
                                            100000)).
                                            getBytes (UTF8))));
                        }
                    });
            }
            catch (NumberFormatException ex)
            {
                ex.printStackTrace ();
            }
        }
    }
}
